import React from 'react';
import { Button, Drawer, Form, Col, Row, Input, DatePicker, Radio, message } from 'antd';
import './App.css';
import axios from 'axios'
import moment from 'moment'

class Todo extends React.Component {
  formRef = React.createRef();
  constructor(prop) {
    super(prop)
    this.state = {
    //   drawerTitle: '新增任务',
      visible: this.props.openTodo,
      type: '0',
      selectedId: ''
    }
  }

  // formRef = React.createRef();

  // 组件第一次渲染完成
  // componentDidMount() {
  //   console.log('第一次渲染完成')
  // }

  //更新
  // static getDerivedStateFromProps(props, state) {
  //   console.log('更新', props, state)
    // this.formRef.current.setFieldsValue({
    //   name: props.formData.name,
    //   status: props.formData.status,
    //   deadline: props.formData.deadline,
    //   content: props.formData.content,
    // });
  // }
  componentDidUpdate() {
    const that = this
    // const formData = this.props.formData
    console.log('更新后会被立即调用')
    that.props.onRef(that)
  }
  componentDidMount() {
    console.log('组件更新渲染')
    // this.props.onRef(this)
    // const formData = this.props.formData
    // this.formRef.current.setFieldsValue({
    //   name: formData.name,
    //   status: formData.status,
    //   deadline: formData.deadline,
    //   content: formData.content
    // });
  }
  // 销毁
  componentWillUnmount() {
    console.log('组件销毁')
  }
  
  // 编辑任务 type '1'
  editTodo(todo, type) {
    console.log('子组件方法被父组件调用', todo)
    if (todo) {
      this.setState({
        type,
        selectedId: todo.key
      })
      // const reg = new RegExp('/', 'g')
      let deadline = new Date(todo.deadline)
      // let currentDate = deadline.toLocaleDateString().replace(reg, '-')
      // let currentTime = deadline.toLocaleTimeString().substring(2)
      // console.log(currentDate, currentTime)
      // const currentDeadline = currentDate + ' ' + currentTime
      console.log(moment(deadline).format("YYYY-MM-DD HH:mm:ss"))

      this.formRef.current.setFieldsValue({
        name: todo.name,
        status: todo.status,
        deadline: moment(deadline),
        content: todo.content
      });
    }
    
  }
  // 关闭任务抽屉
  onClose = (type) => {
    this.formRef.current.resetFields();
    this.props.closeTodo(type)
    // this.formRef.current.setFieldsValue({
    //   name: '',
    //   status: '1',
    //   deadline: '',
    //   content: ''
    // });
  }
  // 重置内容
  onReset = () => {
    this.formRef.current.resetFields();
  };
  // 选择截止日期
  onChange = (date, dateString) => {
    console.log(date, dateString)
    console.log(this.state.formData)
  }
  // 提交表单
  handleSubmit = (values) => {
    const that = this
    console.log('values', values)
    const type = that.state.type
    // axios.post(`${requestUrl}/create`, {
    // type '0' 新增任务 '1' 编辑任务
    if (type === '0') {
      axios.post(`/todoapi/create`, {
        data: values
      })
      .then(function (response) {
        console.log(response);
        if (response.data.type) {
          message.warning('该任务已存在');
        } else {
          message.success('任务添加成功');
        }
        that.onClose(1)
      })
      .catch(function (error) {
        console.log(error);
      });
    } else {
      let editItem = values
      editItem.id = this.state.selectedId
      console.log('修改任务', editItem)
      axios.post(`/todoapi/update`, {
        data: editItem
      })
      .then(function (response) {
        console.log(response);
        message.success('任务修改成功');
        that.onClose(1)
      })
      .catch(function (error) {
        console.log(error);
      });
    }
  }

  render() {
    // let { name, status, deadline, content } = this.props.formData
    // console.log(this.props.formData)
    return (
      <div>
        <Drawer
            title={this.props.drawerTitle}
            width={720}
            onClose={this.onClose}
            visible={this.props.openTodo}
            bodyStyle={{ paddingBottom: 80 }}
          >
            <Form ref={this.formRef} layout="vertical" hideRequiredMark onFinish={this.handleSubmit}
                  // initialValues={{ name:name,status:status,deadline:deadline,content:content }}>
            >
              <Row gutter={16}>
                <Col span={24}>
                  <Form.Item
                    name="name"
                    label="任务名称"
                    // initialValue={name}
                    rules={[{ required: true, message: '任务名称不能为空' }]}
                  >
                    <Input placeholder="请输入任务名称" />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col span={24}>
                  <Form.Item
                    name="status"
                    label="任务状态"
                    // initialValue={status}
                  >
                    <Radio.Group>
                      <Radio value='1'>待办</Radio>
                      <Radio value='2'>开始</Radio>
                      <Radio value='3'>完成</Radio>
                    </Radio.Group>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col span={24}>
                  <Form.Item
                    name="deadline"
                    label="截止时间"
                    // initialValue={deadline}
                    rules={[{ required: true, message: '截止时间不能为空' }]}
                  >
                    <DatePicker onChange={this.onChange} placeholder="请选择截止时间" style={{width: '100%'}} />
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col span={24}>
                  <Form.Item
                    name="content"
                    label="任务内容"
                    // initialValue={content}
                    rules={[
                      {
                        required: true,
                        message: '任务内容不能为空',
                      },
                    ]}
                  >
                    <Input.TextArea rows={4} placeholder="请输入任务内容" />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item>
                <Button onClick={this.onClose} style={{ marginRight: 8 }}>
                  取消
                </Button>
                <Button onClick={this.onReset} style={{ marginRight: 8 }}>
                  重置
                </Button>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </Form.Item>
            </Form>
          </Drawer>
      </div>
    );
  }
}

export default Todo;
